package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.entity.Area;
import net.qhzw.vip.qiyu.entity.LogisticsArea;
import net.qhzw.vip.qiyu.entity.Shop;
import net.qhzw.vip.qiyu.feign.ShopFeignClient;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.mapper.LogisticsAreaMapper;
import net.qhzw.vip.qiyu.service.AreaService;
import net.qhzw.vip.qiyu.service.LogisticsAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class LogisticsAreaServiceImpl extends ServiceImpl<LogisticsAreaMapper, LogisticsArea>
        implements LogisticsAreaService {


    @Autowired
    private LogisticsAreaMapper logisticsAreaMapper;

    @Autowired
    private ShopFeignClient shopFeignClient;

    @Autowired
    private AreaService areaService;

    @Override
    public Long findAaerIdByShopId(Long shopId) {
        return logisticsAreaMapper.selectAaerIdByShopId(shopId);
    }

    @Override
    public boolean allocationOfRegions(LogisticsArea logisticsArea) {
        Long shopId = logisticsArea.getShopId();
        Shop shop = shopFeignClient.findById(shopId).getData();
        if (shop == null) {
            throw new ApiException("获取不到商户信息，请稍后重试！");
        }
        if (4 != shop.getShopType()) {
            throw new ApiException(shop.getShopName() + "该商户暂不支持！");
        }
        Integer count = logisticsAreaMapper.selectCount(new LambdaQueryWrapper<LogisticsArea>().eq(LogisticsArea::getShopId, shopId));
        if (count > 0) {
            remove(new LambdaQueryWrapper<LogisticsArea>().eq(LogisticsArea::getShopId, shopId));
        }
        return save(logisticsArea);
    }

    @Override
    public Area merchantsRgnLst(Long shopId) {
        Shop shop = shopFeignClient.findById(shopId).getData();
        if (shop == null) {
            throw new ApiException("获取不到商户信息，请稍后重试！");
        }
        if (4 != shop.getShopType()) {
            throw new ApiException(shop.getShopName() + "该商户暂不支持！");
        }
        List<Long> areaId = logisticsAreaMapper.selectAreaIdByShopId(shopId);
        Area area = null;
        if (!CollectionUtils.isEmpty(areaId)) {
            area = areaService.findChildsByPid(areaId.get(0));
        }
        return area;
    }
}
